<template>
  <div class="form-container">
    <el-form @submit.prevent="finishEdit" class="medRecord-form" 
      ref="ruleFormRef" style="width: 98%">
      <!-- 基本信息和病情描述 -->
      <el-form-item label="患者姓名:" class="form-item">
        <el-input v-if="userName" type="text" v-model="userName" 
          required style="width: 300px;" :disabled="isFinish"></el-input>
      </el-form-item>
      <el-form-item label="身份证号:" class="form-item">
        <el-input v-if="userName" type="text" v-model="form.idCode" 
          required style="width: 300px;" :disabled="isFinish"></el-input>
      </el-form-item>
      <el-form-item label="病情描述" class="form-item">
        <el-input type="textarea" :disabled="isFinish"
          :autosize="{ minRows: 6, maxRows: 100 }" 
          v-model="form.description" required/>
      </el-form-item>

      <div class="table-container">
        <div class="med-container">
          <!-- 添加药品并显示 -->
          <el-form-item>
            <el-select v-model="selectedMed" filterable default-first-option 
              :reserve-keyword="true" :disabled="isFinish"
              placeholder="选择药品" 
              style="width: 240px; margin-right: 10px">
              <el-option
                v-for="item in medications"
                :key="item.drugId"
                :label="item.name"
                :value="item.name"
                :disabled="item.number === 0"
              >
                <span style="float: left">{{ item.name }}</span>
                <span
                  style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  "
                >
                  {{ item.number }}
                </span>
              </el-option>
            </el-select>
            <el-button type="primary" @click="addDataToMedTable" :disabled="isFinish"
            >添加药品</el-button>
          </el-form-item>

          <el-form-item>
            <el-table :data="medicalTable" border>
              <el-table-column prop="drugName" label="药品名称"/>
              <el-table-column prop="selNum" label="数量">
                <template #default="scope">
                  <el-input-number v-model="scope.row.selNum" :min="1" size="small" 
                    @change="handleNumberChange(scope.$index, scope.row)" 
                    ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button size="small" type="danger" :disabled="isFinish"
                    @click.prevent="handleMedDelete(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>

        <div class="check-container">
          <!-- 添加检查并显示 -->
          <el-form-item>
            <el-select v-model="selectedCheck" filterable default-first-option 
              :reserve-keyword="true" :disabled="isFinish"
              placeholder="选择检查" 
              style="width: 240px; margin-right: 10px">
              <el-option 
                v-for="item in checks" 
                :key="item.checkId" 
                :label="item.name" 
                :value="item.name"/>
            </el-select>
            <el-button type="primary" @click="addDataToCheckTable" :disabled="isFinish"
            >添加检查</el-button>
          </el-form-item>

          <el-form-item>
            <el-table :data="checkTable" border>
              <el-table-column prop="checkName" label="检查名称"/>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button size="small" type="danger" :disabled="isFinish"
                  @click.prevent="handleCheckDelete(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
      </div>
      
      <!-- 提交 -->
      <el-form-item>
        <el-button type="success" native-type="submit" :disabled="userName && isFinish"
        >提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from "@/utils/request.js";

export default {
  data() {
    return {
      drugData: null, // 用于存储从后端获取的药物数据

      userName: this.$route.query.patientName || "",
      form:{
        idCode: this.$route.query.patientIdCard,
        description: "",
        drugs: "",
        checks: "",
        did: localStorage.getItem("dId"),
        time: "",
        arrangeid: "",
      },
      selectedMed: "",
      inputMedNum: "",
      medications: [
        // {drugId: '1659', name: '氟康唑乳膏', price: 95.3, number: 20},
        // {drugId: '1374', name: '福治芬注射液', price: 87.25, number: 10},
        // {drugId: '2876', name: '溴氯噻吨滴眼液', price: 39.99, number: 0}
      ],
      medicalTable: [
        // {drugName: '氟康唑乳膏', selNum: '', number: 20},
      ],

      
      selectedCheck: "",
      checks: [
        // {checkId: '116', name: '尿常规检查', price: 80},
        // {checkId: '267', name: '心电图检查', price: 100},
      ],
      checkTable: [
        // {checkName:"尿常规检查"},
        // {checkName:"心电图检查"},
      ],
      isFinish: false,
    };
  },
  mounted() {
    console.log('当前就诊病人：', this.userName);
    if(!this.userName) this.$message.error('请叫号，选择就诊病人.');
    this.requestDrugs(); // 在组件挂载后立即查询药品数据
    this.requestChecks();
  },
  methods: {
    requestDrugs() {
      request
        .get("/drug/getAllDrug")
        .then((res) => {
            this.medications = res.data;
            console.log('返回药品');
        })
        .catch((error) => {
            // 处理请求错误
            console.error('请求出错:', error);
        });
    },
    requestChecks() {
      request
        .get("/checkList/getAllCheck")
        .then((res) => {
            this.checks = res.data;
            console.log('返回检查');
        })
        .catch((error) => {
            // 处理请求错误
            console.error('请求出错:', error);
        });
    },
    //表格操作
    handleMedDelete(index) {
      this.medicalTable.splice(index, 1);
    },
    handleCheckDelete(index) {
      this.checkTable.splice(index, 1);
    },
    handleNumberChange(index, row) {
      if (row.selNum > row.number) {
        this.$message.error(`药品数量不能超过库存`);
        row.selNum = row.number; // 取消注释此行以将值重置为最大值
      } else {
        console.log(`Row ${index + 1} number changed to ${row.selNum}`);
      }
    },
    //添加药品、检查
    addDataToMedTable() {
      // 检查是否选择了选项和输入了数据
      if (this.selectedMed) {
        const existingMed = this.medicalTable.find(item => item.drugName === this.selectedMed);
        const selectedMedData = this.medications.find(item => item.name === this.selectedMed);
        if (!existingMed) {
          // 如果不存在，则添加新数据
          this.medicalTable.push({
            drugName: this.selectedMed,
            selNum: 1,
            number: selectedMedData.number
          });
          
          // 清空输入框和选择器
          this.selectedMed = '';
        } else {
          // 如果已存在，则显示警告消息
          this.$message.warning('该药品已存在于列表中.');
        }
      } else {
        // 如果没有选择药品，则显示警告消息
        this.$message.warning('请选择药品.');
      }
    },
    addDataToCheckTable() {
      if (this.selectedCheck) {
        const existingCheck = this.checkTable.some(item => item.checkName === this.selectedCheck);
        if (!existingCheck) {
          this.checkTable.push({
            checkName: this.selectedCheck
          });
          this.selectedCheck = '';
        } else {
          this.$message.warning('该检查项已存在于列表中.');
        }
      } else {
        this.$message.warning('请选择检查项.');
      }
    },
    //post操作
    formatMedicalTable(table) {
      let result = '';
      table.forEach(item => {
        result += `${item.drugName} ${item.selNum}\n`;
      });
      console.log(result);
      return result;
    },
    formatCheckTable(table) {
      let result = '';
      table.forEach(item => {
        result += `${item.checkName}\n`;
      });
      console.log(result);
      return result;
    },
    getCurrentTime() {
      // 获取当前时间
      let currentTime = new Date();
      
      // 格式化时间
      const year = currentTime.getFullYear();
      const month = String(currentTime.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
      const day = String(currentTime.getDate()).padStart(2, '0');
      const hours = String(currentTime.getHours()).padStart(2, '0');
      const minutes = String(currentTime.getMinutes()).padStart(2, '0');
      const seconds = String(currentTime.getSeconds()).padStart(2, '0');
      
      // 拼接成所需格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    async finishEdit() {
      console.log("userName:", this.userName);
      console.log("userIdCard:", this.form.idCode);
      //创建一个病例+开药单
      this.form.drugs = this.formatMedicalTable(this.medicalTable);
      this.form.checks = this.formatCheckTable(this.checkTable);
      this.form.time = this.getCurrentTime();
      this.form.arrangeid = localStorage.getItem("currentArrangeId");
      console.log("time:", this.form.time);
      console.log("arrangeid:", this.form.arrangeid);

      console.log("form: ",this.form);
      try{
        await request
        .get("/patientRecord/addPatientRecordAndMedicalRecord", {
          params: this.form
        })
        .then((res) => {
            console.log("已完成病历创建",res);
        })
        .catch((e) => {
            console.log(e);
        });

        //完成就诊
        const params1 = new URLSearchParams();
        params1.append("idCard", this.form.idCode);
        params1.append("dId", this.form.did);

        await request
          .post("/arrange/updateIfFinish", params1)
          .then((res) => {
              console.log("创建病历成功, 完成就诊isFinish",res);
          })
          .catch((e) => {
              console.log(e);
          });

        this.isFinish = true;
        localStorage.removeItem('currentArrangeId')
        
        this.$message.success('已完成病历创建.');
      } catch (error) {
        // 处理错误，可以记录日志、显示错误消息等
        console.error("在创建病历或更新就诊状态时发生错误:", error);
        this.$message.error('创建病历或更新就诊状态时出错.');
      }
    }
  },
};
</script>

<style scoped>
/* 添加样式 */
.form-container {
  max-height: calc(80vh);
  overflow-y: auto; /* 允许垂直滚动 */
}
.table-container {
  display: flex;
  flex-wrap: nowrap; /* 防止子元素换行 */
  justify-content: space-between; /* 子元素之间的间距（可选） */
}
 
.med-container, .check-container {
  flex: 1; /* 各占一半宽度 */
  padding: 10px; /* 可选的，为了美观和间距 */
  box-sizing: border-box; /* 确保padding不会增加容器的宽度 */
}
</style>
